<template>
  
    <!-- #ifdef MP-WEIXIN -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    <!-- #endif -->
    <view class="category-page">
      <!-- 搜索栏 -->
      <view class="search-section">
        <view class="search-container">
          <!-- <view class="back-btn" @click="goBack">
            <image class="back-icon" src="/static/Images/goods/Fanhui.png" mode="aspectFit"></image>
          </view> -->
          <view class="search-input" @click="goToSearch">
            <image class="search-icon" src="/static/Images/index/Search.png" mode="aspectFit"></image>
            <text class="search-placeholder">搜索商品名</text>
            <view class="search-btn" @click.stop="goToSearch">
              <text class="search-btn-text">搜索</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 商品分类列表 -->
      <view class="category-container">
        <!-- 左侧一级分类列表 -->
        <scroll-view class="category-left-list" scroll-y="true">
          <view 
            v-for="(category, index) in categoryList" 
            :key="index"
            class="category-item"
            :class="{ active: selectedCategoryIndex === index }"
            :style="selectedCategoryIndex === index ? { backgroundImage: `url(${backgroundImages.selected})` } : {}"
            @click="onCategoryClick(category, index)"
          >
            <text class="category-name">{{ category.name }}</text>
          </view>
        </scroll-view>
        
        <!-- 右侧二级分类网格 -->
        <view class="category-right-content">
          <scroll-view class="subcategory-grid" scroll-y="true">
            <view class="subcategory-grid-container">
              <view 
                v-for="(subCategory, sIndex) in currentSubCategories" 
                :key="sIndex"
                class="subcategory-item"
                @click="onSubCategoryClick(subCategory, selectedCategory)"
              >
                <view class="subcategory-circle">
                  <image v-if="subCategory.icon" :src="subCategory.icon" class="subcategory-icon" mode="aspectFit" />
                  <text v-else class="subcategory-placeholder">{{ subCategory.name.charAt(0) }}</text>
                </view>
                <text class="subcategory-name">{{ subCategory.name }}</text>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
      
      <!-- 底部指示器 -->
      <view class="home-indicator"></view>
    </view>
  <tab-bar :active="1" />
</template>

<script>
import TabBar from '@/components/TabBar.vue'
import { goodsApi } from '@/utils/api'
import { getImageUrl } from '@/config/api'

export default {
  components: {
    'tab-bar': TabBar,
  },
  data() {
    return {
      selectedCategoryIndex: 0, // 当前选中的一级分类索引
      // 新增：完整分类列表（包含一级与二级）
      allCategoryList: [],
      // 左侧一级分类列表（pid=0）
      categoryList: [],
      loading: false,
      // 状态栏高度
      statusBarHeight: 0
    }
  },
  computed: {
    // 当前选中的分类
    selectedCategory() {
      return this.categoryList[this.selectedCategoryIndex] || {}
    },
    // 当前选中分类的二级分类列表：从完整列表中过滤 pid=选中一级分类id
    currentSubCategories() {
      const parentId = this.selectedCategory?.id
      if (!parentId) return []
      return this.allCategoryList.filter(item => Number(item.pid) === Number(parentId))
    },
    // 背景图片计算属性
    backgroundImages() {
      return {
        selected: getImageUrl('/static/Images/goods/Xuanzhong.png')
      }
    }
  },
  created() {
    // #ifdef MP-WEIXIN
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync()
    // 获取胶囊按钮信息
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    // 计算状态栏高度：系统状态栏高度 + 胶囊按钮高度 + 额外间距
    this.statusBarHeight = (systemInfo.statusBarHeight || 0) + (menuButtonInfo.height || 32) + 8
    // #endif
    
    this.fetchCategories()
  },
  methods: {
    async fetchCategories() {
      try {
        this.loading = true
        const res = await goodsApi.getGoodsClass()
        const list = Array.isArray(res?.data) ? res.data : []
        // 统一映射结构并数字化 pid
        const mapped = list.map(item => ({
          id: item.id,
          name: item.name,
          icon: item.icon || '',
          desc: item.desc || '',
          sort: item.sort,
          status: item.status,
          type: item.type,
          pid: Number(item.pid) || 0
        }))
        // 保存完整列表
        this.allCategoryList = mapped
        // 左侧仅展示一级分类（pid=0）
        this.categoryList = mapped.filter(c => Number(c.pid) === 0)
        // 默认选中第一个一级分类
        this.selectedCategoryIndex = 0
      } catch (e) {
        console.error('获取商品分类失败', e)
        uni.showToast({ title: `获取分类失败：${e.message || e}`, icon: 'none' })
      } finally {
        this.loading = false
      }
    },
    // 点击一级分类
    onCategoryClick(category, index) {
      this.selectedCategoryIndex = index
      // 右侧 currentSubCategories 为计算属性，会自动根据 selectedCategory 刷新
    },
    // 点击二级分类
    onSubCategoryClick(subCategory, parentCategory) {
      const cid = subCategory?.id;
      if (!cid) {
        uni.showToast({ title: '未获取到分类ID', icon: 'none' });
        return;
      }
      // 跳转到商品列表，展示该分类下全部商品
      uni.navigateTo({
        url: `/pages/goods/goodslist?class_id=${encodeURIComponent(cid)}`
      });
    },
    // 跳转到搜索页面
    goToSearch() {
      uni.navigateTo({
        url: '/pages/index/search'
      });
    }
  }
}
</script>

<style scoped>
/* 状态栏样式 */
.status-bar {
  width: 100%;
  background-color: #FF7B80;
}

.category-page {
  width: 752rpx;
  margin: 0 auto;
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 状态栏 */
.status-bar {
  height: 44px;
  background: linear-gradient(180deg, #FF7B80 0%, rgba(244,234,234,0) 100%);
  padding: 0 20px;
  display: flex;
  align-items: center;
}

.status-content {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time {
  font-size: 17px;
  font-weight: 600;
  color: #000000;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 5px;
}

.signal, .wifi, .battery {
  font-size: 14px;
  color: #000000;
}

/* 搜索栏 */
.search-section {
  width: 752rpx;
  padding: 48rpx;
  background-color: #ffffff;
  margin: 0 auto;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 16rpx;
  width: 656rpx;
}

.back-btn {

  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.back-icon {
  max-width: 20px;
  max-height: 20px;
}

.search-input {
  flex: 1;
  max-height: 36px;
  background-color: #f5f5f5;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  padding: 0 16rpx;
  position: relative;
  height: 64rpx;
}

.search-icon {
  max-width: 16px;
  max-height: 16px;
  flex-shrink: 0;
}

.search-placeholder {
  font-size: 14px;
  color: #999999;
  flex: 1;
}

.search-btn {
  background-color: #ff4757;
  border-radius: 32px;
  display: flex;
  padding: 10rpx;
  align-items: center;
  justify-content: center;
  position: absolute;
  right: 5rpx;
  height: 40rpx;
  max-height: 28px;
  width: 96rpx;
}

.search-btn-text {
  font-size: 14px;
  color: #ffffff;
  font-weight: 500;
}

/* 分类容器 */
.category-container {
  flex: 1;
  display: flex;
  background-color: #ffffff;
  
}

/* 左侧一级分类列表 */
.category-left-list {
  width: 176rpx;
  background-color: #f8f8f8;
}

.category-item {
  padding: 24rpx 16rpx;
  border-bottom: 1px solid #e8e8e8;
  cursor: pointer;
  transition: background-color 0.2s;
  text-align: center;
  border-right: 1px solid #e8e8e8;
}

.category-item:active {
  background-color: #e8e8e8;
}

.category-item.active {
  background-color: #ffffff;
  background-repeat: no-repeat;
  background-position: left center;
  background-size: 0.25rem;
  border-right: none;
  z-index: 10;
  position: relative;
}

.category-name {
  font-size: 14px;
  color: #333333;
  font-weight: 400;
}

.category-item.active .category-name {
  color: #ff4757;
  font-weight: 500;
}

/* 右侧二级分类内容区 */
.category-right-content {
  flex: 1;
  background-color: #ffffff;
}

.subcategory-grid {
  height: 100%;
  padding: 20px;
}

.subcategory-grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.subcategory-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  transition: transform 0.2s, opacity 0.2s;
  margin-left: -1.6rem;
}

.subcategory-item:active {
  transform: scale(0.95);
  opacity: 0.7;
  background-color: #f5f5f5;
}

.subcategory-circle {
  width: 60px;
  height: 60px;
  background-color: #e8e8e8;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.subcategory-icon {
  width: 36px;
  height: 36px;
}

.subcategory-placeholder {
  font-size: 20px;
  font-weight: 500;
  color: #666;
}

.subcategory-name {
  font-size: 13px;
  color: #333333;
  text-align: center;
  font-weight: 400;
  padding-top: 16rpx;
  padding-bottom: 16rpx;
}

/* 底部指示器 */
.home-indicator {
  height: 34px;
  background-color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.home-indicator::after {
  content: '';
  width: 134px;
  height: 5px;
  background-color: #000000;
  border-radius: 3px;
}
</style>